from django.shortcuts import render, redirect
from django import forms
from www import models
from utils.bootstrap import BootStrapForm
from utils.pager import Pagination

class PriceModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.PricePolicy
        fields = ['count', 'price']


def price_add(request):
    origin = request.GET.get('redirect')
    if request.method == 'GET':
        form = PriceModelForm()
        return render(request, 'form2.html', {'form': form})
    form = PriceModelForm(request.POST)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})
    form.save()
    return redirect(origin)


def price_delete(request, id):
    origin = request.GET.get('redirect')
    if request.method == 'GET':
        return render(request, 'delete.html',{'origin':origin})
    instance = models.PricePolicy.objects.filter(id=id).delete()
    return redirect(origin)


def price_list(request):
    queryset = models.PricePolicy.objects.all().order_by('count')
    pager = Pagination(request, queryset)
    return render(request, 'price_list.html', {'pager': pager})


def price_edit(request, id):
    origin = request.GET.get('redirect')
    instance = models.PricePolicy.objects.filter(id=id).first()
    if request.method == 'GET':
        form = PriceModelForm(instance=instance)
        return render(request, 'form2.html', {'form': form})
    form = PriceModelForm(request.POST, instance=instance)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})
    form.save()
    return redirect(origin)
